//
//  OrderStatusView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI
import Foundation


struct OrderStatusView: View {
    @EnvironmentObject var dataManager: DataManager
    @Binding var selectedSegment: Int
    @State private var selectedOrder: Order?
    @State private var showPickupAlert = false
    
    init(selectedSegment: Binding<Int> = .constant(0)) {
        self._selectedSegment = selectedSegment
    }
    
    private let segments = ["current", "history"]
    
    var currentOrders: [Order] {
        dataManager.orders.filter { order in
            order.status != .completed && order.status != .cancelled
        }.sorted { $0.orderDate > $1.orderDate }
    }
    
    var historyOrders: [Order] {
        dataManager.orders.filter { order in
            order.status == .completed || order.status == .cancelled
        }.sorted { $0.orderDate > $1.orderDate }
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // 顶部导航
            topNavigation
            
            // 分段控制器
            segmentedControl
            
            // 订单列表
            ordersList
        }
        .background(
            LinearGradient(
                colors: [
                    Color(red: 0.0, green: 0.0, blue: 0.0),
                    Color(red: 0.05, green: 0.02, blue: 0.08),
                    Color(red: 0.08, green: 0.04, blue: 0.12),
                    Color(red: 0.12, green: 0.06, blue: 0.15),
                    Color(red: 0.15, green: 0.08, blue: 0.18),
                    Color(red: 0.18, green: 0.10, blue: 0.20),
                    Color(red: 0.20, green: 0.12, blue: 0.22),
                    Color(red: 0.22, green: 0.14, blue: 0.25)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()
        )
        .sheet(item: $selectedOrder) { order in
                OrderDetailView(order: order)
                    .environmentObject(dataManager)
            }
            .alert(isPresented: $showPickupAlert) {
                let orderNumber = currentOrders.first?.orderNumber ?? ""
                let lang = dataManager.currentLanguage == "zh"
                return Alert(
                    title: Text(dataManager.currentLanguage == "zh" ? "取餐通知" : "Pickup Notification"),
                    message: Text(orderNumber + "\n" + (lang ? "请去前台取餐" : "Please go to the counter to pick up")),
                    dismissButton: .default(Text("OK")) {
                        // 跳转到History
                        dataManager.shouldNavigateToOrdersHistory = true
                    }
                )
            }
    }
    
    // MARK: - 顶部导航
    private var topNavigation: some View {
        HStack {
            // Logo
            Image(systemName: "fork.knife.circle.fill")
                .font(.title2)
                .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            
            Text(dataManager.currentLanguage == "zh" ? "订单" : "Orders")
                .font(.title2)
                .fontWeight(.bold)
                .foregroundColor(.white)
            
            Spacer()
            
            Image("Logo")
                .resizable()
                .scaledToFit()
                .frame(width: 35, height: 35)
                .onTapGesture {
                    if !currentOrders.isEmpty {
                        // 更新第一个订单状态为completed
                        if let firstOrder = currentOrders.first {
                            // 确保用户已登录并有认证令牌
                            if dataManager.currentUser == nil {
                                // 如果用户未登录，先进行自动登录
                                if !dataManager.tryAutoLogin() {
                                    // 如果自动登录失败，使用游客模式的临时令牌
                                    let tempToken = "guest-" + UUID().uuidString
                                    APIClient.shared.setAuthToken(tempToken)
                                }
                            }
                            
                            dataManager.updateOrderStatus(firstOrder.id, status: .completed)
                        }
                        showPickupAlert = true
                    }
                }
        }
        .padding(.horizontal, 20)
        .padding(.top, 10)
        .padding(.bottom, 15)
    }
    
    // MARK: - 分段控制器
    private var segmentedControl: some View {
        HStack(spacing: 0) {
            ForEach(0..<segments.count, id: \.self) { index in
                Button(action: {
                    selectedSegment = index
                }) {
                    VStack(spacing: 8) {
                        Text(segmentTitle(for: index))
                            .font(.subheadline)
                            .fontWeight(.medium)
                            .foregroundColor(selectedSegment == index ? Color(red: 1.0, green: 0.6, blue: 0.2) : .gray)
                        
                        Rectangle()
                            .fill(selectedSegment == index ? Color(red: 1.0, green: 0.6, blue: 0.2) : Color.clear)
                            .frame(height: 2)
                    }
                }
                .frame(maxWidth: .infinity)
            }
        }
        .padding(.horizontal, 20)
        .padding(.bottom, 20)
    }
    
    // MARK: - 订单列表
    private var ordersList: some View {
        ScrollView {
            LazyVStack(spacing: 15) {
                let orders = selectedSegment == 0 ? currentOrders : historyOrders
                
                if orders.isEmpty {
                    emptyStateView
                } else {
                    ForEach(orders) { order in
                        OrderRowView(order: order) {
                            selectedOrder = order
                        }
                    }
                }
            }
            .padding(.horizontal, 20)
            .padding(.bottom, 100)
        }
    }
    
    // MARK: - 空状态视图
    private var emptyStateView: some View {
        VStack(spacing: 20) {
            Image(systemName: selectedSegment == 0 ? "clock" : "doc.text")
                .font(.system(size: 60))
                .foregroundColor(.gray)
            
            Text(selectedSegment == 0 ? 
                 (dataManager.currentLanguage == "zh" ? "暂无进行中的订单" : "No current orders") :
                 (dataManager.currentLanguage == "zh" ? "暂无历史订单" : "No order history"))
                .font(.headline)
                .foregroundColor(.gray)
            
            Text(selectedSegment == 0 ? 
                 (dataManager.currentLanguage == "zh" ? "快去点餐吧！" : "Start ordering now!") :
                 (dataManager.currentLanguage == "zh" ? "您还没有完成任何订单" : "You haven't completed any orders yet"))
                .font(.subheadline)
                .foregroundColor(.gray)
                .multilineTextAlignment(.center)
        }
        .padding(.top, 80)
    }
    
    // MARK: - 辅助方法
    private func segmentTitle(for index: Int) -> String {
        switch index {
        case 0:
            return dataManager.currentLanguage == "zh" ? "进行中" : "Current"
        case 1:
            return dataManager.currentLanguage == "zh" ? "历史订单" : "History"
        default:
            return ""
        }
    }
}

// MARK: - 订单行视图
struct OrderRowView: View {
    let order: Order
    let onTap: () -> Void
    @EnvironmentObject var dataManager: DataManager
    
    // 检测是否只有Cash Voucher
    private var hasOnlyCashVoucher: Bool {
        order.items.count == 1 && order.items.first?.menuItem.name == AppConfig.Cart.voucherPackageName
    }
    
    var body: some View {
        Button(action: onTap) {
            VStack(spacing: 15) {
                // 订单头部信息
                HStack {
                    VStack(alignment: .leading, spacing: 5) {
                        Text(order.orderNumber)
                            .font(.system(size: 14))
                            .fontWeight(.semibold)
                            .foregroundColor(.white)
                        
                        Text(formatDate(order.orderDate))
                            .font(.caption)
                            .foregroundColor(.gray)
                    }
                    
                    Spacer()
                    
                    VStack(alignment: .trailing, spacing: 5) {
                        Text("S$\(order.total, specifier: "%.2f")")
                            .font(.headline)
                            .fontWeight(.bold)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        
                        OrderStatusBadge(status: order.status)
                    }
                }
                
                // 订单项目预览
                orderItemsPreview
                
                // 用餐信息
                diningInfo
            }
            .padding(20)
            .background(
                RoundedRectangle(cornerRadius: 15)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color(red: 0.15, green: 0.15, blue: 0.16).opacity(0.95),  // 半透明亮黑带极微蓝
                                Color(red: 0.18, green: 0.18, blue: 0.18).opacity(0.9),   // 半透明亮黑
                                Color(red: 0.22, green: 0.20, blue: 0.15).opacity(0.85),  // 半透明金色
                                Color(red: 0.12, green: 0.10, blue: 0.08).opacity(0.95)   // 半透明深金
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
            )
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    // MARK: - 订单进度视图
    private var orderProgressView: some View {
        VStack(spacing: 10) {
            HStack {
                ForEach(OrderStatus.allCases.filter { $0 != .cancelled }, id: \.self) { status in
                    Circle()
                        .fill(order.status.progressValue >= status.progressValue ? Color(red: 1.0, green: 0.6, blue: 0.2) : Color.gray)
                        .frame(width: 12, height: 12)
                    
                    if status != OrderStatus.allCases.filter({ $0 != .cancelled }).last {
                        Rectangle()
                            .fill(order.status.progressValue > status.progressValue ? Color(red: 1.0, green: 0.6, blue: 0.2) : Color.gray)
                            .frame(height: 2)
                    }
                }
            }
            
            HStack {
                ForEach(OrderStatus.allCases.filter { $0 != .cancelled }, id: \.self) { status in
                    Text(dataManager.currentLanguage == "zh" ? status.displayName : status.englishDisplayName)
                        .font(.caption)
                        .foregroundColor(order.status.progressValue >= status.progressValue ? Color(red: 1.0, green: 0.6, blue: 0.2) : .gray)
                        .frame(maxWidth: .infinity)
                }
            }
        }
    }
    
    // MARK: - 订单项目预览
    private var orderItemsPreview: some View {
        VStack(alignment: .leading, spacing: 8) {
            Text(dataManager.currentLanguage == "zh" ? "订单内容" : "Order Items")
                .font(.subheadline)
                .fontWeight(.medium)
                .foregroundColor(.white)
            
            VStack(spacing: 5) {
                ForEach(Array(order.items.prefix(3)), id: \.id) { item in
                    HStack {
                        Text("\(item.quantity)x")
                            .font(.caption)
                            .foregroundColor(.gray)
                            .frame(width: 25, alignment: .leading)
                        
                        Text(dataManager.currentLanguage == "zh" ? item.menuItem.name : item.menuItem.englishName)
                            .font(.caption)
                            .foregroundColor(.white)
                            .lineLimit(1)
                        
                        Spacer()
                        
                        Text("S$\(item.totalPrice, specifier: "%.2f")")
                            .font(.caption)
                            .foregroundColor(.gray)
                    }
                }
                
                if order.items.count > 3 {
                    Text(dataManager.currentLanguage == "zh" ? "还有 \(order.items.count - 3) 项..." : "And \(order.items.count - 3) more...")
                        .font(.caption)
                        .foregroundColor(.gray)
                        .padding(.top, 2)
                }
            }
        }
    }
    
    // MARK: - 用餐信息
    private var diningInfo: some View {
        VStack(spacing: 5) {
            HStack {
                Image(systemName: hasOnlyCashVoucher ? "giftcard" : (order.diningType == DiningType.dineIn ? "fork.knife" : "bag"))
                    .font(.caption)
                    .foregroundColor(.gray)
                
                Text(hasOnlyCashVoucher ? "N/A" : order.displayOrderType(language: dataManager.currentLanguage))
                    .font(.caption)
                    .foregroundColor(.gray)
                
                if !hasOnlyCashVoucher && order.diningType == DiningType.dineIn, let tableNumber = order.tableNumber {
                    Text("• \(dataManager.currentLanguage == "zh" ? "桌号" : "Table") \(tableNumber)")
                        .font(.caption)
                        .foregroundColor(.gray)
                }
                
                Spacer()
                
                Text(dataManager.currentLanguage == "zh" ? order.paymentMethod.rawValue : order.paymentMethod.englishName)
                    .font(.caption)
                    .foregroundColor(.gray)
            }
            
            // 预订信息显示 - 所有预订订单都显示预约信息
            if order.isReservation, let reservationTime = order.reservationTime {
                VStack(alignment: .leading, spacing: 3) {
                    HStack {
                        Image(systemName: "calendar.badge.clock")
                            .font(.caption)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        
                        Text(dataManager.currentLanguage == "zh" ? "预订时间: " : "Reservation: ")
                            .font(.caption)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        
                        Text(BusinessHoursManager.formatReservationTime(reservationTime, language: dataManager.currentLanguage))
                            .font(.caption)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        
                        Spacer()
                    }
                    
                    // 预订详细信息
                    if let partySize = order.reservationPartySize {
                        HStack {
                            Image(systemName: "person.2")
                                .font(.caption)
                                .foregroundColor(.gray)
                            
                            Text(dataManager.currentLanguage == "zh" ? "\(partySize)人" : "\(partySize) guests")
                                .font(.caption)
                                .foregroundColor(.gray)
                            
                            if let seatingType = order.reservationSeatingType {
                                Text("•")
                                    .font(.caption)
                                    .foregroundColor(.gray)
                                
                                Text(dataManager.currentLanguage == "zh" ? seatingType.chineseName : seatingType.englishName)
                                    .font(.caption)
                                    .foregroundColor(.gray)
                            }
                            
                            Spacer()
                        }
                    }
                }
            }
        }
    }
    
    // MARK: - 辅助方法
    private func formatDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM/dd HH:mm"
        return formatter.string(from: date)
    }
}

// MARK: - 订单状态徽章
struct OrderStatusBadge: View {
    let status: OrderStatus
    @EnvironmentObject var dataManager: DataManager
    
    var body: some View {
        Text(dataManager.currentLanguage == "zh" ? status.displayName : status.englishDisplayName)
            .font(.caption)
            .fontWeight(.medium)
            .foregroundColor(statusColor)
            .padding(.horizontal, 8)
            .padding(.vertical, 4)
            .background(
                RoundedRectangle(cornerRadius: 8)
                    .fill(statusColor.opacity(0.2))
            )
    }
    
    private var statusColor: Color {
        switch status {
        case .pending:
            return .orange
        case .confirmed:
            return .blue
        case .preparing:
            return .yellow
        case .ready:
            return .green
        case .completed:
            return .green
        case .cancelled:
            return .red
        }
    }
}

// MARK: - 订单详情视图
struct OrderDetailView: View {
    let order: Order
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.presentationMode) var presentationMode
    @State private var showingRatingView = false
    
    // 检测是否只有Cash Voucher
    private var hasOnlyCashVoucher: Bool {
        order.items.count == 1 && order.items.first?.menuItem.name == AppConfig.Cart.voucherPackageName
    }
    
    var body: some View {
        VStack {
            HStack {
                Spacer()
                Text(dataManager.currentLanguage == "zh" ? "订单详情" : "Order Details")
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                Spacer()
                Button(dataManager.currentLanguage == "zh" ? "完成" : "Done") {
                    presentationMode.wrappedValue.dismiss()
                }
                .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            }
            .padding()
            
            ScrollView {
                VStack(spacing: 20) {
                    orderBasicInfo
                    
                    
                    
                    orderItemsDetail
                    
                    priceBreakdown
                    
                    diningInformation
                    
                    actionButtons
                }
                .padding(20)
                .padding(.bottom, 20)
            }
            .background(
                LinearGradient(
                    colors: [
                        Color(red: 0.12, green: 0.12, blue: 0.12),
                        Color(red: 0.18, green: 0.16, blue: 0.15)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
        }
        .sheet(isPresented: $showingRatingView) {
            OrderRatingView(order: order)
                .environmentObject(dataManager)
        }
    }
    
    // MARK: - 订单基本信息
    private var orderBasicInfo: some View {
        VStack(spacing: 15) {
            HStack {
                VStack(alignment: .leading, spacing: 5) {
                    Text(order.orderNumber)
                        .font(.system(size: 15))
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                    
                    Text(formatFullDate(order.orderDate))
                        .font(.subheadline)
                        .foregroundColor(.gray)
                }
                
                Spacer()
                
                OrderStatusBadge(status: order.status)
            }
            
            if order.status == .ready {
                HStack {
                    Image(systemName: "bell.fill")
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    
                    Text(dataManager.currentLanguage == "zh" ? "您的美食已准备好，请前往前台取餐！" : "Your food is ready, please go to the counter to pick up!")
                        .font(.subheadline)
                        .foregroundColor(.white)
                        .multilineTextAlignment(.leading)
                }
                .padding(15)
                .background(
                    RoundedRectangle(cornerRadius: 10)
                        .fill(Color(red: 1.0, green: 0.6, blue: 0.2).opacity(0.2))
                        .overlay(
                            RoundedRectangle(cornerRadius: 10)
                                .stroke(Color(red: 1.0, green: 0.6, blue: 0.2), lineWidth: 1)
                        )
                )
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    // MARK: - 订单状态进度
    private var orderStatusProgress: some View {
        VStack(spacing: 15) {
            Group {
                    if #available(iOS 16.0, *) {
                        Text(dataManager.currentLanguage == "zh" ? "订单进度" : "Order Progress")
                            .font(.headline)
                    .fontWeight(.semibold)
                            .foregroundColor(.white)
                    } else {
                        Text(dataManager.currentLanguage == "zh" ? "订单进度" : "Order Progress")
                            .font(.headline)
                            .bold()
                            .foregroundColor(.white)
                    }
                }
            
            VStack(spacing: 20) {
                ForEach(OrderStatus.allCases.filter { $0 != .cancelled }, id: \.self) { status in
                    HStack(spacing: 15) {
                        Circle()
                            .fill(order.status.progressValue >= status.progressValue ? Color(red: 1.0, green: 0.6, blue: 0.2) : Color.gray)
                            .frame(width: 20, height: 20)
                            .overlay(
                                Image(systemName: order.status.progressValue >= status.progressValue ? "checkmark" : "")
                                    .font(.caption.bold())
                                    .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                            )
                        
                        VStack(alignment: .leading, spacing: 2) {
                            Text(dataManager.currentLanguage == "zh" ? status.displayName : status.englishDisplayName)
                                .font(.subheadline)
                                .fontWeight(.medium)
                                .foregroundColor(order.status.progressValue >= status.progressValue ? .white : .gray)
                            
                            Text(statusDescription(for: status))
                                .font(.caption)
                                .foregroundColor(.gray)
                        }
                        
                        Spacer()
                        
                        if order.status == status {
                            ProgressView()
                                .progressViewStyle(CircularProgressViewStyle(tint: Color(red: 1.0, green: 0.6, blue: 0.2)))
                                .scaleEffect(0.8)
                        }
                    }
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    // MARK: - 订单项目详情
    private var orderItemsDetail: some View {
        VStack(alignment: .leading, spacing: 15) {
            Text(dataManager.currentLanguage == "zh" ? "订单内容" : "Order Items")
                .font(.headline)
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            VStack(spacing: 12) {
                ForEach(order.items) { item in
                    HStack(alignment: .top, spacing: 15) {
                        Text("\(item.quantity)x")
                            .font(.subheadline)
                            .foregroundColor(.gray)
                            .frame(width: 30, alignment: .leading)
                        
                        VStack(alignment: .leading, spacing: 5) {
                            Text(dataManager.currentLanguage == "zh" ? item.menuItem.name : item.menuItem.englishName)
                                .font(.subheadline)
                                .fontWeight(.medium)
                                .foregroundColor(.white)
                            
                            if let meatType = item.selectedMeatType {
                                Text(dataManager.currentLanguage == "zh" ? meatType.rawValue : meatType.englishName)
                                    .font(.caption)
                                    .foregroundColor(.gray)
                            }
                            
                            if !item.specialInstructions.isEmpty {
                                Text(item.specialInstructions)
                                    .font(.caption)
                                    .foregroundColor(.gray)
                                    .italic()
                            }
                        }
                        
                        Spacer()
                        
                        Text("S$\(item.totalPrice, specifier: "%.2f")")
                            .font(.subheadline)
                            .fontWeight(.medium)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    }
                    
                    if item.id != order.items.last?.id {
                        Divider()
                            .background(Color.gray.opacity(0.3))
                    }
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    // MARK: - 价格明细
    private var priceBreakdown: some View {
        VStack(alignment: .leading, spacing: 15) {
            Text(dataManager.currentLanguage == "zh" ? "价格明细" : "Price Breakdown")
                .font(.headline)
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            VStack(spacing: 10) {
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "小计" : "Subtotal")
                        .foregroundColor(.gray)
                    Spacer()
                    Text("S$\(order.subtotal, specifier: "%.2f")")
                        .foregroundColor(.white)
                }
                
                HStack {
    Text(dataManager.currentLanguage == "zh" ? "折扣" : "Discount")
        .foregroundColor(.gray)
    Spacer()
    Text("-S$\(order.couponDiscount, specifier: "%.2f")")
        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
}

HStack {
    Text("\(dataManager.currentLanguage == "zh" ? "积分抵扣" : "Points Discount") (\(order.pointsUsed))")
        .foregroundColor(.gray)
    Spacer()
    Text("-S$\(order.pointsDiscount, specifier: "%.2f")")
        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
}

HStack {
    Text("GST (9%)")
        .foregroundColor(.gray)
    Spacer()
    Text("S$\(order.tax, specifier: "%.2f")")
        .foregroundColor(.white)
}
                
                Divider()
                    .background(Color.gray)
                
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "总计" : "Total")
                        .font(.headline)
                        .fontWeight(.semibold)
                        .foregroundColor(.white)
                    Spacer()
                    Text("S$\(order.total, specifier: "%.2f")")
                        .font(.title2)
                        .fontWeight(.bold)
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                }
                
                HStack {
    Text(dataManager.currentLanguage == "zh" ? "获得积分" : "Points Earned")
        .foregroundColor(.gray)
    Spacer()
    Text("\(order.pointsEarned > 0 ? "+" : "")\(order.pointsEarned)")
        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
}
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    // MARK: - 用餐信息
    private var diningInformation: some View {
        VStack(alignment: .leading, spacing: 15) {
            Text(dataManager.currentLanguage == "zh" ? "用餐信息" : "Dining Information")
                .font(.headline)
                .fontWeight(.semibold)
                .foregroundColor(.white)
            
            VStack(spacing: 10) {
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "用餐方式" : "Dining Type")
                        .foregroundColor(.gray)
                    Spacer()
                    Text(hasOnlyCashVoucher ? "N/A" : order.displayOrderType(language: dataManager.currentLanguage))
                        .font(.caption)
                        .foregroundColor(.gray)
                }
                
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "桌号" : "Table Number")
                        .foregroundColor(.gray)
                    Spacer()
                    Text(order.diningType == DiningType.dineIn ? (order.tableNumber ?? "N/A") : "N/A")
                        .foregroundColor(.white)
                }
                
                // 预订信息显示
                if order.isReservation, let reservationTime = order.reservationTime {
                    HStack {
                        Text(dataManager.currentLanguage == "zh" ? "预订时间" : "Reservation Time")
                            .foregroundColor(.gray)
                        Spacer()
                        Text(BusinessHoursManager.formatReservationTime(reservationTime, language: dataManager.currentLanguage))
                            .foregroundColor(.white)
                    }
                    
                    if let partySize = order.reservationPartySize {
                        HStack {
                            Text(dataManager.currentLanguage == "zh" ? "预订人数" : "Party Size")
                                .foregroundColor(.gray)
                            Spacer()
                            Text(dataManager.currentLanguage == "zh" ? "\(partySize)人" : "\(partySize) guests")
                                .foregroundColor(.white)
                        }
                    }
                    
                    if let seatingType = order.reservationSeatingType {
                        HStack {
                            Text(dataManager.currentLanguage == "zh" ? "座位类型" : "Seating Type")
                                .foregroundColor(.gray)
                            Spacer()
                            Text(dataManager.currentLanguage == "zh" ? seatingType.chineseName : seatingType.englishName)
                                .font(.caption)
                                .foregroundColor(.gray)
                        }
                    }
                    
                    if let specialRequests = order.reservationSpecialRequests, !specialRequests.isEmpty {
                        VStack(alignment: .leading, spacing: 5) {
                            HStack {
                                Text(dataManager.currentLanguage == "zh" ? "特殊要求" : "Special Requests")
                                    .foregroundColor(.gray)
                                Spacer()
                            }
                            Text(specialRequests)
                                .foregroundColor(.white)
                                .font(.caption)
                                .multilineTextAlignment(.leading)
                        }
                    }
                }
                
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "支付方式" : "Payment Method")
                        .foregroundColor(.gray)
                    Spacer()
                    Text(dataManager.currentLanguage == "zh" ? order.paymentMethod.rawValue : order.paymentMethod.englishName)
                        .foregroundColor(.white)
                }
            }
        }
        .padding(20)
        .background(
            RoundedRectangle(cornerRadius: 15)
                .fill(
                    LinearGradient(
                        colors: [
                            Color(red: 0.15, green: 0.15, blue: 0.15),
                            Color(red: 0.1, green: 0.1, blue: 0.1),
                            Color(red: 0.05, green: 0.05, blue: 0.05)
                        ],
                        startPoint: .top,
                        endPoint: .bottom
                    )
                )
        )
    }
    
    // MARK: - 操作按钮
    private var actionButtons: some View {
        Button(action: {
            showingRatingView = true
        }) {
            Text(dataManager.currentLanguage == "zh" ? "评价订单" : "Rate Order")
                .font(.headline)
                .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                .frame(maxWidth: .infinity)
                .padding(.vertical, 15)
                .background(
                    RoundedRectangle(cornerRadius: 12)
                        .fill(Color(red: 1.0, green: 0.6, blue: 0.2))
                )
        }
    }
    
    // MARK: - 辅助方法
    private func formatFullDate(_ date: Date) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日 HH:mm"
        if dataManager.currentLanguage != "zh" {
            formatter.dateFormat = "MMM dd, yyyy HH:mm"
        }
        return formatter.string(from: date)
    }
    
    private func statusDescription(for status: OrderStatus) -> String {
        if dataManager.currentLanguage == "zh" {
            switch status {
            case .pending:
                return "等待餐厅确认"
            case .confirmed:
                return "订单已确认"
            case .preparing:
                return "厨房正在制作"
            case .ready:
                return "可以取餐了"
            case .completed:
                return "订单已完成"
            case .cancelled:
                return "订单已取消"
            }
        } else {
            switch status {
            case .pending:
                return "Waiting for confirmation"
            case .confirmed:
                return "Order confirmed"
            case .preparing:
                return "Kitchen is preparing"
            case .ready:
                return "Ready for pickup"
            case .completed:
                return "Order completed"
            case .cancelled:
                return "Order cancelled"
            }
        }
    }
}

// MARK: - 订单评价视图
struct OrderRatingView: View {
    let order: Order
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.presentationMode) var presentationMode
    @State private var rating = 5
    @State private var comment = ""
    
    var body: some View {
        NavigationView {
            VStack(spacing: 30) {
                // 评分区域
                VStack(spacing: 20) {
                    Text(dataManager.currentLanguage == "zh" ? "请为本次用餐体验评分" : "Please rate your dining experience")
                        .font(.headline)
                        .foregroundColor(.white)
                        .multilineTextAlignment(.center)
                    
                    HStack(spacing: 10) {
                        ForEach(1...5, id: \.self) { star in
                            Button(action: {
                                rating = star
                            }) {
                                Image(systemName: star <= rating ? "star.fill" : "star")
                                    .font(.title)
                                    .foregroundColor(star <= rating ? Color(red: 1.0, green: 0.6, blue: 0.2) : .gray)
                            }
                        }
                    }
                    
                    Text(ratingText)
                        .font(.subheadline)
                        .foregroundColor(.gray)
                }
                
                // 评论区域
                VStack(alignment: .leading, spacing: 15) {
                    Text(dataManager.currentLanguage == "zh" ? "分享您的用餐感受" : "Share your dining experience")
                        .font(.headline)
                        .foregroundColor(.white)
                    
                    TextField(
                        dataManager.currentLanguage == "zh" ? "请输入您的评价..." : "Enter your review...",
                        text: $comment
                    )
                    .foregroundColor(.white)
                    .padding(15)
                    .background(
                        RoundedRectangle(cornerRadius: 10)
                            .stroke(Color(red: 1.0, green: 0.6, blue: 0.2), lineWidth: 1)
                    )
                    .lineLimit(5)
                }
                
                Spacer()
                
                // 提交按钮
                Button(action: submitRating) {
                    Text(dataManager.currentLanguage == "zh" ? "提交评价" : "Submit Review")
                        .font(.headline)
                        .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 15)
                        .background(
                            RoundedRectangle(cornerRadius: 12)
                                .fill(Color(red: 1.0, green: 0.6, blue: 0.2))
                        )
                }
            }
            .padding(20)
            .background(
                LinearGradient(
                    colors: [
                        Color(red: 0.12, green: 0.12, blue: 0.12),
                        Color(red: 0.18, green: 0.16, blue: 0.15)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
            .navigationTitle(dataManager.currentLanguage == "zh" ? "评价订单" : "Rate Order")
            .navigationBarTitleDisplayMode(.inline)
            .navigationBarItems(leading: 
                Button(dataManager.currentLanguage == "zh" ? "取消" : "Cancel") {
                    presentationMode.wrappedValue.dismiss()
                }
            )
        }
    }
    
    private var ratingText: String {
        if dataManager.currentLanguage == "zh" {
            switch rating {
            case 1: return "非常不满意"
            case 2: return "不满意"
            case 3: return "一般"
            case 4: return "满意"
            case 5: return "非常满意"
            default: return ""
            }
        } else {
            switch rating {
            case 1: return "Very Dissatisfied"
            case 2: return "Dissatisfied"
            case 3: return "Average"
            case 4: return "Satisfied"
            case 5: return "Very Satisfied"
            default: return ""
            }
        }
    }
    
    private func submitRating() {
        // 这里可以添加提交评价的逻辑
        presentationMode.wrappedValue.dismiss()
    }
}

#Preview {
    OrderStatusView()
        .environmentObject(DataManager.shared)
}